package com.slm.report.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dlong.rep.dlsidebar.DLSideBar;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.slm.mylibrary.base.BaseMvpActivity;
import com.slm.mylibrary.utils.DialogUtils;
import com.slm.mylibrary.utils.IDialogAlertCallback;
import com.slm.report.adapter.StudentNameAdapter;
import com.slm.report.databinding.ActivityHomePageBinding;
import com.slm.report.db.DuShuInfoBean;
import com.slm.report.db.DuShuInfoBean_Table;
import com.slm.report.db.SignInInfoBean;
import com.slm.report.db.SignInInfoBean_Table;
import com.slm.report.db.StudentInfoBean;
import com.slm.report.db.VisionDataInfo;
import com.slm.report.db.VisionDataInfo_Table;
import com.slm.report.state.HomePageViewModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ProjectName: My Application
 * @Package: com.slm.report.ui
 * @ClassName: HomePageActivity
 * @Description: java类作用描述
 * @Author: 王丹丹
 * @CreateDate: 2020/5/28 10:17
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/5/28 10:17
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class HomePageActivity extends BaseMvpActivity<HomePageViewModel> implements MaterialSearchBar.OnSearchActionListener {

    private ActivityHomePageBinding viewBinding;
    private List<StudentInfoBean> infoBeanList = new ArrayList<>();
    private String searchKey = "";
    private long mExitTime = 0;
    private StudentNameAdapter nameAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewBinding = ActivityHomePageBinding.inflate(LayoutInflater.from(this));
        setContentView(viewBinding.getRoot());
        viewBinding.listData.setVerticalScrollBarEnabled(false);
        viewBinding.listData.setFastScrollEnabled(false);
        viewBinding.sbIndex.setOnTouchingLetterChangedListener(mSBTouchListener);
        nameAdapter = new StudentNameAdapter(this, infoBeanList, new StudentNameAdapter.OnDelDataCallBack() {
            @Override
            public void deleteData(final StudentInfoBean infoBean) {
                DialogUtils.obtainCommonDialog("确定删除" + infoBean.getName() + "信息？", new IDialogAlertCallback() {
                    @Override
                    public void sure() {
                        SQLite.delete().from(VisionDataInfo.class)
                                .where(VisionDataInfo_Table.studentId.eq(infoBean.getId()))
                                .executeUpdateDelete();
                        SQLite.delete().from(DuShuInfoBean.class)
                                .where(DuShuInfoBean_Table.studentId.eq(infoBean.getId()))
                                .executeUpdateDelete();
                        SQLite.delete().from(SignInInfoBean.class)
                                .where(SignInInfoBean_Table.studentId.eq(infoBean.getId()))
                                .executeUpdateDelete();
                        infoBean.delete();
                        infoBeanList.remove(infoBean);
                        nameAdapter.notifyDataSetChanged();
                        ToastUtils.showShort("删除成功");
                    }
                }).show(getSupportFragmentManager());
            }
        });
        viewBinding.listData.setAdapter(nameAdapter);
        viewBinding.searchBar.setOnSearchActionListener(this);
        viewBinding.searchBar.setCardViewElevation(10);
        mViewModel.obtainStudentInfos(searchKey);
        mViewModel.list.observe(this, new Observer<List<StudentInfoBean>>() {
            @Override
            public void onChanged(List<StudentInfoBean> studentInfoBeans) {
                infoBeanList.clear();
                infoBeanList.addAll(studentInfoBeans);
                Collections.sort(infoBeanList, new StudentInfoBean.ComparatorPY());
                nameAdapter.notifyDataSetChanged();
            }
        });

        viewBinding.addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startActivityForResult(HomePageActivity.this, AddStudentInfoActivity.class, 8);
            }
        });

    }


    /**
     * 右侧index选项监听
     */
    private DLSideBar.OnTouchingLetterChangedListener mSBTouchListener = new DLSideBar.OnTouchingLetterChangedListener() {
        @Override
        public void onTouchingLetterChanged(String str) {
            //触摸字母列时,将品牌列表更新到首字母出现的位置
            if (!infoBeanList.isEmpty()) {
                for (int i = 0; i < infoBeanList.size(); i++) {
                    if (infoBeanList.get(i).getFisrtSpell().compareToIgnoreCase(str) == 0) {
                        viewBinding.listData.setSelection(i);
                        break;
                    }
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            mViewModel.obtainStudentInfos(searchKey);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onSearchStateChanged(boolean enabled) {
    }

    @Override
    public void onSearchConfirmed(CharSequence text) {
        searchKey = text.toString();
        mViewModel.obtainStudentInfos(searchKey);
    }

    @Override
    public void onButtonClicked(int buttonCode) {
        switch (buttonCode) {
            case MaterialSearchBar.BUTTON_BACK:
                viewBinding.searchBar.closeSearch();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
